import { MomService } from './../../../@core/services/mom/mom.service';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DialogService, DrawerService, IDrawerOpenResult, TableWidthConfig } from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { ProcessService } from 'src/app/@core/services/process/process.service';
import { TechnologyRouteViewComponent } from '../technology-route/technology-route-view/technology-route-view.component';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { PreViewmMomComponent } from './pre-viewm-mom/pre-viewm-mom.component';

@Component({
  selector: 'app-mom',
  templateUrl: './mom.component.html',
  styleUrls: ['./mom.component.scss']
})
export class MOMComponent {
  tabledata:any;//表格数据
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  checkedIds = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  msgs: { severity: any; summary: any; content: any; }[];
  config = {
    id: 'Add-Dirctoy-Type',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  SearchTerm:string='';
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  checkboxList = [];
  allChecked = false;
  halfChecked = false;
  optionsStatus = [
    '已核准',
    '未核准'
  ]
  IsApproval:string=null;
  results: IDrawerOpenResult;
  constructor(private Router:Router,private dialogService: DialogService,private SharedMethodService:SharedMethodService,private ProcessService:ProcessService,private MomService:MomService,private drawerService: DrawerService,){}
  ngOnInit(): void {
    this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.pager.total=data.totalCount;
    })
  }
  dataTableOptions = {
    columns: [
      {
        field: 'type',
        header: '物料名称',
        fieldType: 'text'
      },
      {
        field: 'type',
        header: '物料编码',
        fieldType: 'text'
      },
      {
        field: '版本',
        header: '版本',
        fieldType: 'text'
      },
      {
        field: '工艺路线',
        header: '工艺路线',
        fieldType: 'text'
      },
      {
        field: '开始日期',
        header: '开始日期',
        fieldType: 'text'
      },
      {
        field: '结束日期',
        header: '结束日期',
        fieldType: 'text'
      },
      {
        field: 'rizhi',
        header: '日志',
        fieldType: 'text',
      },
      {
        field: 'enabled',
        header: '核准',
        fieldType: 'boolean',
        fixedRight:'0px'
      },
    ]
  };//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field: 'type',
      width: '230px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
  ];//表格宽度配置
  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
    this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.pager.total=data.totalCount;
    })
  }//切换页码
  pageSizeChange($event: any){
    this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.pager.total=data.totalCount;
    })
  }//改变每页显示数量
  Delete(id:any,dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该生产方法？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
              this.MomService.DeleteMOMs([id]).subscribe((data:any)=>{
                results.modalInstance.hide();
                this.showToast('success','删除成功','该生产方法删除成功')
                this.checkedIds=[];
                this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
                  this.tabledata=data.items;
                  this.pager.total=data.totalCount;
                })
              },(error:any)=>{
                this.showToast('error','删除失败',error.error.message)
              }
              )
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//删除
  Deletes(dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该生产方法？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            const hasApproval = this.checkboxList.some((item: any) => item.isApproval === true);
            if (!hasApproval) {
              this.MomService.DeleteMOMs(this.checkedIds).subscribe((data:any)=>{
                results.modalInstance.hide();
                this.showToast('success','删除成功','生产方法删除成功')
                this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
                  this.tabledata=data.items;
                  this.pager.total=data.totalCount;
                })
              },(error:any)=>{
                this.showToast('error','删除失败',error.error.message)
              }
              )
            }else{
              this.showToast('error','删除失败','存在已核准的单据，无法删除')
            }

          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//删除
  Approval(id:any){
    this.MomService.ApprovalMOM(id).subscribe((data:any)=>{
      this.showToast('success','核准成功','生产方法核准成功')
      this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
        this.tabledata=data.items;
        this.pager.total=data.totalCount;
      })
    },(error:any)=>{
      this.showToast('error','核准失败',error.error.message)
    })
  }//核准
  UnApproval(id:any){
    this.MomService.UnApprovalMOM(id).subscribe((data:any)=>{
      this.showToast('success','取消核准成功','生产方法取消核准成功')
      this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
        this.tabledata=data.items;
        this.pager.total=data.totalCount;
      })
    },(error:any)=>{
      this.showToast('error','取消核准失败',error.error.message)
    })
  }//取消核准
  edit(id:any){
    this.Router.navigate(['/pages/process/mom/edit-mom/',id])
  }//编辑
  filter(){
    this.pager.pageIndex=1;
    this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.pager.total=data.totalCount;
    })
  }//筛选
  reset(){
    this.SearchTerm='';
    this.IsApproval=null;
    this.MomService.GetMethodOfManufactures(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize,this.IsApproval).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.pager.total=data.totalCount;
    })
  }//重置
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  cleared(){
    this.SharedMethodService.cleared(this.checkedIds,this.tabledata,this.datatable).subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable);
  }//单选
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable,'momId').subscribe((data:any)=>{
      this.checkedIds=data;
    })
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe((data:any)=>{
      this.checkboxList=data;
    })
  }//获取选中行
  view(technologyRouteId:any,dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      width:'700px',
      title: '工艺详情',
      data:technologyRouteId,
      content: TechnologyRouteViewComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    })
  }
  openDrawer(monId:any) {
    this.MomService.GetLogsByMOMId(monId).subscribe((data:any)=>{
      const logData = data
      const columns =  [
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text'
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text'
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text'
        }
      ]

      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: {data:logData,columns:columns},
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {

        },
      });
      }
    )

  }
  preview(rowItem:any,dialogtype?: string) {
    const nodes = rowItem.momProcesses;
    const results = this.dialogService.open({
      width: '1000px',
      title: 'MOM预览',
      backdropCloseable: false,
      data: {
        nodes: nodes,
        tabActiveId: '物料',
      },
      content: PreViewmMomComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
